<?php

class AuthController extends Zend_Controller_Action
{
    protected function _getAuthAdapter() {
        
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
        
        $authAdapter->setTableName('utilisateurs')
            ->setIdentityColumn('uti_nom')
            ->setCredentialColumn('uti_motdepasse')
            ->setCredentialTreatment('SHA1(?)');
            
        
        return $authAdapter;
    }
    
    protected function _process($values)
    {
        // Création d'un objet utilisateur
        $utilisateursMapper = new Application_Model_MapperUtilisateur();
        $utilisateur = $utilisateursMapper->newModel($values);
        $utilisateur->setMotDePasse($values['motdepasse']);
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($utilisateur);
        if ($result->isValid()) {
            return true;
        }     
        return false;
    }
    
    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->redirector('index', 'index'); // back to login page
    }

    public function indexAction()
    {
        $form = new Application_Form_Login();
        $request = $this->getRequest();
        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                if ($this->_process($form->getValues())) {
                    // We're authenticated! Redirect to the home page
                    $this->_helper->redirector('index', 'index');
                }            
                else {
                    $form->getElement('motdepasse')->addError('Authentification invalide');
                }   
            }
        }
        $this->view->form = $form;
    }


}

